package com.spring.boot.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.session.jdbc.JdbcOperationsSessionRepository;
import org.springframework.session.jdbc.config.annotation.web.http.JdbcHttpSessionConfiguration;
import org.springframework.session.web.http.CookieHttpSessionStrategy;
import org.springframework.session.web.http.SessionRepositoryFilter;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.DispatcherType;
import javax.sql.DataSource;

@Configuration
public class CommonConfiguration {


    @Bean("springSessionRepositoryFilter")
    public SessionRepositoryFilter springSessionRepositoryFilter(@Qualifier("defaultDataSource") DataSource dataSource
            ,@Qualifier("defaultTransactionManager") DataSourceTransactionManager dataSourceTransactionManager){
        JdbcOperationsSessionRepository sessionRepository = new JdbcOperationsSessionRepository(dataSource, dataSourceTransactionManager);
        SessionRepositoryFilter sessionRepositoryFilter = new SessionRepositoryFilter(sessionRepository);
        // 使用cookie 作为 session的依托
        sessionRepositoryFilter.setHttpSessionStrategy(new CookieHttpSessionStrategy());
        return sessionRepositoryFilter;
    }

    @Bean
    public FilterRegistrationBean filter3(){

        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        DelegatingFilterProxy springSessionRepositoryFilter = new DelegatingFilterProxy("springSessionRepositoryFilter");
        registrationBean.setFilter(springSessionRepositoryFilter);
        registrationBean.setName("springSessionRepositoryFilter");
        registrationBean.addUrlPatterns("/*");
        registrationBean.setDispatcherTypes(DispatcherType.REQUEST,DispatcherType.ERROR);
        registrationBean.setOrder(-5);
        return registrationBean;
    }



    /*@Bean("jdbcHttpSessionConfiguration")
    public JdbcHttpSessionConfiguration jdbcHttpSessionConfiguration(){
        return new JdbcHttpSessionConfiguration();
    }*/
}
